package com.example.newbook.config;
import com.alibaba.fastjson.JSONObject;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @program: littleRedBook240509
 * @author: tenghw
 * @create: 2024-05-11 02:50
 * @Version 1.0
 * @description:
 **/
public class FixedNameJsonFilePipeline implements Pipeline {

    private final String filePath;

    public FixedNameJsonFilePipeline(String directory, String fixedFileName) {
        this.filePath = directory + File.separator + fixedFileName + ".json";
    }

    @Override
    public void process(ResultItems resultItems, Task task) {
        // 生成的json内容格式为： {key=value}
        //try (FileWriter writer = new FileWriter(filePath, true)) {
        //    // 这里简单地将结果转换为JSON字符串写入文件，实际应用中可能需要更复杂的序列化逻辑
        //    String jsonStr = resultItems.getAll().toString();
        //    writer.write(jsonStr);
        //} catch (IOException e) {
        //    e.printStackTrace();
        //}

        // 生成的json内容格式为： {key: value}
        try (FileWriter writer = new FileWriter(filePath)) {
            // 将ResultItems转换为Map，然后使用Fastjson转换为JSON字符串
            JSONObject json = new JSONObject(resultItems.getAll());
            writer.write(json.toJSONString());
            writer.write("\n"); // 每个item间添加换行符
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}